package net.godcode.olivenotes.entities;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 * PostDAOHibernate
 * 
 * @author Chris Lewis Dec 26, 2007 <chris@thegodcode.net>
 * @version $Id: PostDAOHibernate.java 32 2008-01-22 15:14:31Z burningodzilla $
 */
public class PostDAOHibernate extends GenericHibernateDAO<Post, Long> implements PostDAO {
	
	public PostDAOHibernate(Session session) {
		super();
		setSession(session);
	}
	
	@SuppressWarnings("unchecked")
	public Post findById(long id, boolean published) {
		return (Post)getSession().createCriteria(Post.class)
		.add(Restrictions.eq("published", published))
		.add(Restrictions.idEq(id)).uniqueResult();
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * @param count The maximum number of posts to return.
	 * @return The list most recent posts.
	 */
	public List<Post> findRecent(int count, boolean published) {
		Query q = getSession().getNamedQuery("Post.RECENT_PUBLISHED");
		q.setMaxResults(count);
		return (List<Post>)q.list();
	}
	
	@SuppressWarnings("unchecked")
	public Post findLast(boolean published) {
		Query q = getSession().getNamedQuery(published ? "Post.RECENT_PUBLISHED" : "Post.RECENT");
		q.setMaxResults(1);
		List<Post> posts = (List<Post>)q.list();
		return posts.size() > 0 ? posts.get(0) : null;
	}
	
	@SuppressWarnings("unchecked")
	/*
	 * Currently we use the query api because the HQL method wasn't giving objects
	 * of the proper class. 
	 */
	public List<Post> findByTag(String tag, boolean published) {
		return (List<Post>)getSession().createCriteria(Post.class)
			.add(Restrictions.eq("published", published))
			.createCriteria("tags")
				.add(Restrictions.eq("name", tag)).list();
	}
	
	public Post findByCreatedAndName(int year, int month, int day, String name) {
		//TODO ug
		Query q = getSession().createQuery("from Post as post where post.name=:name and year(post.created)=:year and month(post.created)=:month and day(post.created)=:day");
		q.setParameter("year", year).setParameter("month", month).setParameter("day", day);
		return (Post)q.setParameter("name", name).uniqueResult();
	}
}